package com.simpletour.qa.user.biz;

import com.simpletour.qa.common.base.BaseBiz;
import com.simpletour.qa.common.entity.Role;
import com.simpletour.qa.common.entity.User;
import com.simpletour.qa.user.repository.RoleJpaRepository;
import com.simpletour.qa.user.repository.UserJpaRepository;
import com.simpletour.qa.user.util.SHAEncrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.security.NoSuchAlgorithmException;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;

/**
 * @author zhaohw
 * @date 2018-06-20 14:11
 */
@Service
public class UserBiz extends BaseBiz<UserJpaRepository,User,Integer> {

    @Autowired
    private UserJpaRepository jpaRepository;

    @Autowired
    private RoleJpaRepository roleJpaRepository;

    public User findUserByUsername(String username){
       return jpaRepository.findUserByUsername(username);
    }

    public Page<User> findAllByPage(Integer page,Integer size){
        Sort sort = new Sort(Sort.Direction.ASC, "username");
        Pageable pageParam = PageRequest.of(page,size,sort);
        return jpaRepository.findAll(pageParam);
    }

    @Transactional(rollbackOn = Exception.class)
    public void addUserWithRoleInfo(User user) throws NoSuchAlgorithmException,DataIntegrityViolationException {
        Optional<Role> role = roleJpaRepository.findById(Role.DEFAULT_ROLE_ID);
        if (role.isPresent()){
            Set<Role> roleSet = new HashSet<>(1);
            roleSet.add(role.get());
            user.setRoles(roleSet);
        }
        user.init();
        String encrypt = SHAEncrypt.encryptSHA(user.getPassword());
        user.setPassword(encrypt);
        jpaRepository.save(user);
    }
}
